﻿<?php

namespace Classes;

use Classes\db\DBConnection;
use Classes\UserPrincipal;
use PDO;
use Exception;

class Login {
	public static function loginUser($inputUsername, $inputPassword) {
		try {
			if ($_POST ['username'] == '' || $_POST ['password'] == '') {
				throw new Exception ( "<p>Невалидни данни.</p>" );
			}
			
			$con = DBConnection::getDBConnection ();
			$stmt = "SELECT * FROM user WHERE user_name = :USERNAME";
			
			$statement = $con->prepare ( $stmt );
			$statement->bindValue ( ':USERNAME', $inputUsername, PDO::PARAM_STR );
			
			$statement->execute ();
			
			if ($statement->rowCount () == 1) {
				
				$row = $statement->fetch ();
				if (md5 ( $inputPassword ) == $row ['password']) {
					session_start ();
					$userPrincial = new UserPrincipal ( $row ['user_name'], $row ['user_id'], $row ['email'], $row ['active'], $row ['city'], $row ['favorite_club'], $row ['playing'], $row ['playing_club'], $row ['rank'] );
					
					$_SESSION ['userPrincipal'] = $userPrincial;
					header ( "Location: home.php" );
				} else {
					throw new Exception ( "<p>Невалидни данни.</p>" );
				}
			} else {
				throw new Exception ( "<p>Невалидни данни.</p>" );
			}
		} catch ( Exception $e ) {
			echo '<p>' . $e->getMessage () . '</p>';
		}
	}
}